package Offer.offer2016;

import domain.TreeNode;

public class Test27 {

    public static void main(String[] args) {

    }

    public TreeNode ConvertBSTToBiList(TreeNode root) {
        if (root == null)
            return null;
        root.left = max(root.left);
        if (root.left != null) {
            root.left.right = root;
        }
        root.right = min(root.right);
        if (root.right != null) {
            root.right.left = root;
        }
        while (root.left != null) {
            root = root.left;
        }
        return root;
    }

    public static TreeNode max(TreeNode root) {
        if (root == null)
            return null;
        root.left = max(root.left);
        if (root.left != null) {
            root.left.right = root;
        }
        root.right = min(root.right);
        if (root.right != null) {
            root.right.left = root;
        }
        while (root.right != null) {
            root = root.right;
        }
        return root;
    }

    public static TreeNode min(TreeNode root) {
        if (root == null)
            return null;
        root.left = max(root.left);
        if (root.left != null) {
            root.left.right = root;
        }
        root.right = min(root.right);
        if (root.right != null) {
            root.right.left = root;
        }
        while (root.left != null) {
            root = root.left;
        }
        return root;
    }
}	
